package com.css.apps.base.post.action;

import com.css.apps.base.log.model.LogConstant;
import com.css.apps.base.log.model.LogPart;
import com.css.apps.base.post.model.SPost;
import com.css.apps.base.post.model.SPostRole;
import com.css.apps.base.user.service.UserHelper;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.Ajax;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;

@SuppressWarnings("serial")
public class DelPostRole extends AdminAction {

	private static Log log = LogFactory.getLog(DelPostRole.class);
	private String ids; // 角色uuid
	private String postId; // 用户uuid

	@SuppressWarnings("unchecked")
	@Override
	protected String adminGo() {
		TransactionCache tx = null;
		try {
			if (StringHelper.isEmpty(ids) || StringHelper.isEmpty(postId)) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}
			List<String> listIds = StringHelper.strToList(ids);
			List<String> sb = new QueryCache("select a.uuid from SPostRole a where a.postId= :postId and a.roleId in (:listIds) ")
							.setParameter("postId", postId).setParameter("listIds", listIds).list();
			tx = new TransactionCache();
			tx.delete(SPostRole.class, sb);
			tx.commit();
			SPost post = QueryCache.get(SPost.class, postId);
			post.getPostRoleList().removeAll();
			// 跟此岗位相关的用户需要清空菜单信息
			QueryCache qc = new QueryCache("select a.userId from SUserPost a where a.postId =:postId")
					.setParameter("postId", postId);
			List<String> userIdList = qc.list();
			UserHelper helper = new UserHelper();
			for (String userId : userIdList) {
				helper.clearUserMenuCache(userId);
			}
			// SPostItem.getRoleList(postId);

			for (String postRoleid : sb) {
				LogPart lp = new LogPart();
				lp.setOpObjType(SPostRole.class.getName());
				lp.setOpObjId(postRoleid);
				lp.setRelObjType(SPost.class.getName());
				lp.setRelObjId(postId);
				lp.setOpType(LogConstant.LOG_TYPE_DELETE);
				lp.setLogLevel(LogConstant.LOG_LEVEL_IMPORTANT);
				lp.setLogData("");
				lp.setResult(LogConstant.RESULT_SUCCESS);
				lp.save();
			}

			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return Action.SUCCESS;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			if (tx != null) {
				tx.rollback();
			}
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			return Action.ERROR;
		}
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getPostId() {
		return postId;
	}

	public void setPostId(String postId) {
		this.postId = postId;
	}

}
